package com.cakeshop.service.impl;

import com.cakeshop.dao.CommentDao;
import com.cakeshop.dao.impl.CommentDaoImpl;
import com.cakeshop.model.Comment;
import com.cakeshop.service.CommentService;

import java.sql.SQLException;
import java.util.List;

/**
 * @author nineice
 * @date 2021/8/23 21:31
 */
public class CommentServiceImpl implements CommentService {

    private CommentDao commentDao = new CommentDaoImpl();

    @Override
    public void likes(Comment comment, int flag) {
        try {
            if (flag > 0) {
                comment.setLikeNum(comment.getLikeNum() + 1);
            } else {
                comment.setLikeNum(comment.getLikeNum() - 1);
            }
            commentDao.updateById(comment);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void noLikes(Comment comment, int flag) {
        try {
            if (flag > 0) {
                comment.setNoLikeNum(comment.getNoLikeNum() + 1);
            } else {
                comment.setNoLikeNum(comment.getNoLikeNum() - 1);
            }
            commentDao.updateById(comment);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteComment(Comment comment) {
        try {
            commentDao.deleteById(comment.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void appendComment(Comment comment) {
        try {
            commentDao.insertComment(comment);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void appendReply(int id, Comment reply) {
        try {
            // 获取原评论
            Comment original = commentDao.findById(id);
            StringBuilder sb = new StringBuilder();
            if (original.getReply() != null && !original.getReply().isEmpty()) {
                sb.append(original.getReply());
            }

            // 写入回复
            sb.append(reply);
            original.setReply(sb.toString());

            // 更新原评论数据
            commentDao.updateById(original);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Comment> getAllComment() {
        try {
            return commentDao.findAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Comment getCommentById(int id) {
        try {
            return commentDao.findById(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }
}
